var uitgelicht_interval = 8000;
var cur_uitgelicht_id = 0;

(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

String.prototype.chunk = function(n) {
    var ret = [];
    for(var i=0, len=this.length; i < len; i += n) {
       ret.push(this.substr(i, n))
    }
    return ret
};


function makePie(){
	$('#result-chart').html('');
	var r = new Raphael("result-chart", 405, 240);
    r.g.txtattr.font = "12px 'Fontin Sans', Fontin-Sans, sans-serif";
    
    //r.g.text(150, 20, "Poll results").attr({"font-size": 20});
	
    var values = [],
	labels = [];
	$("#pollresults tr").each(function () {
		values.push(parseInt($("td", this).text(), 10));
		labels.push($("th", this).text());
	});

    /*
    console.log(labels);
     
    $(labels).each(function(){
       if ($(this).length>10){
           console.log($(this).toString().chunk(5).join( String.fromCharCode(13)));
           console.log('te lang');
       }
    });
    */
	
	//console.log(labels);
	//console.log(values);
	
	$(values).each(function(item){
		if(this==0){
			//console.log(teller);
			values[item]= 0.000001;
		}
	});
	
	if($.inArray(100, values)!=-1){
		correctIndex = parseInt($.inArray(100, values));
		//console.log($.inArray(0.000001, values));
		//console.log();
		//console.log(labels[correctIndex]);
		values = [100];
		labels = [labels[correctIndex]];
	}
	//console.log(labels);
	//console.log(values);
	//labels = ['test',];
	//values = [100,];
	//$("#pollresults table").hide();
	//mypie = raphael("result-chart", 300, 300).pieChart(150, 150, 100, values, labels, "#fff");
	mypie = r.g.piechart(120, 140, 90, values, {
		legend: labels,
        //legendpos: "south"
	});
	mypie.hover(function () {
		//console.log(this.value);
        this.sector.stop();
        this.sector.scale(1.1, 1.1, this.cx, this.cy);
		//console.log(this.value);
        if (this.label) {
            this.label[0].stop();
            this.label[0].scale(1.5);
            this.label[1].attr({"font-weight": 800});
		}
		//this.label[1].tspan.innerHTML = 'hoi';
		$(this.label[1].node).find('tspan').append(' ('+this.value+'%)');
		
    }, function () {
        this.sector.animate({scale: [1, 1, this.cx, this.cy]}, 500, "bounce");
        if (this.label) {
            this.label[0].animate({scale: 1}, 500, "bounce");
            this.label[1].attr({"font-weight": 400});
        }
		old_text = $(this.label[1].node).find('tspan').text()
		$(this.label[1].node).find('tspan').text(old_text.substring(0, old_text.lastIndexOf(' (')));
    });

    $('#result-chart svg text').each(function(){

        currentText = $(this).find('tspan').text();
        //console.log(currentText);
        currentColor = $(this).prev().attr('fill');
        //console.log($(currentColor));
        $('#results-table th').each(function(){
            if ($(this).html()==currentText){
                $(this).html('<div style="float: left; width: 20px; height: 20px; margin-right: 5px; background-color: '+currentColor+';">&nbsp;</div> '+$(this).html());
            }
        });
        //console.log($(this).innerHTML());
    });


}

$(document).ready(function() {
	//var r = Raphael("result-chart");
	//console.log(r);
	if ($('#close-poll').length > 0) {
		makePie();
	}
	
	if ($('#presplayer').length > 0) {
		url = $('#presplayer').html();
	
	
		jwplayer("pres-container").setup({
					file: url,
			        height: 400,
			        width: 780,
					frontcolor: '333333',
					screencolor: "ffffff",
					backcolor: "ffffff"
					
			    });
		/*
			    
		//console.log($('#presplayer'));
		//console.log(url);
		//$('#presplayer').attr('src', url);

		//$('#presplayer')[0].load();
		
		var html = "";
		html += '<video id="presVid" width="780" height="400" controls="controls">';
		html += '<source src="'+url+'"  type="video/mp4" />';
		html += '</video>';
		
		$("#presplayer").html(html);
		$("#presplayer").fadeIn();
		
		$('#presVid').attr('src', url);
		$('#presVid')[0].load();
		*/	
	}
	
	
	
	$('#close-poll').click(function(){
		//console.log($(this).html());
		if ($(this).html() == "X") {
			$.cookie($(this).attr('class'), "true", {
				expires: 70
			});
			$('.poll').css('overflow', "hidden");
			$('.poll').animate({
				height: "14px"
			}, 500);
			$(this).html("show");
		}else{
			$.cookie($(this).attr('class'), null);
			$('.poll').css('height', '14px');
			$('.poll').removeClass('hide');
			$('.poll').animate({
				height: "300px"
			}, 500);
			$(this).html("X");
		}
		return false;
	});	
	
	$('#view-poll-results').click(function(){
		$('#pollform form').fadeOut(function(){
			$('#result-chart').css({
				position: "inherit"
			});
			$('#result-chart').animate({
				marginLeft: "-60px"
			}, 1000 );
		});
		$(this).fadeOut();
		return false;
	});
	
	$('#submit-vote').click(function(){
		if ($('#pollform form').css('display') == "none") {
			$('#result-chart').animate({
				marginLeft: "-1960px"
			}, 1000, function(){
				$('#pollform form').fadeIn();
				$('#result-chart').css({
					position: "absolute"
				});
			});
			
		}else {
			vote = $(".poll-form input[@name='pollanswer']:checked").val();
			csrf = $(".poll-form input:hidden").val();
			if (vote != "") {
				url = $(".poll-form").attr('action');
				//console.log(url);
				$.ajax({
					type: 'POST',
					url: url + "vote/",
					data: 'csrfmiddlewaretoken=' + csrf + '&choice=' + vote,
					success: function(data){
						if (data == "already voted") {
							alert('You already voted... You can only vote once...');
						}
						if (data == "choice accepted") {
							totalvotes = parseInt($('#results-table').attr('class'))+1;
							$('#results-table').find('td').each(function(i, el) {
					            votes = 0;
								
								votes = $(el).attr('class');
								//console.log($(el).attr('id'));
								if ($(el).attr('id')=="choice-"+vote){
									//console.log('keuze 1 ophogen');
									votes = parseInt(votes) + 1;
								}else{
									//console.log('niet DE keuze...');
									votes = parseInt(votes) + 0;
								}
								perc = (votes/totalvotes)*100+'%';
								//console.log('Huidige aantal votes: ' + votes);
								//console.log('totaal:' + totalvotes);
								//console.log(perc);
								$(el).html(perc);
					        })
							$('#view-poll-results').fadeOut();
							makePie();
							$('#submit-vote').fadeOut();
							$('#pollform form').fadeOut(function(){
								$('#result-chart').css({
									position: "inherit"
								});
								$('#result-chart').animate({
									marginLeft: "-60px"
								}, 1000 );
							});
						}
					}
				});
			}
		}
		return false;
	});

function load_uitgelicht(){
	$.getJSON("/get-uitgelicht/?not="+cur_uitgelicht_id,
        function(data){
	      //console.log(data);
		  cur_uitgelicht_id = data.fac_id;
		  uni_naam = data.uni_naam;
		  uni_omschrijving = data.uni_omschrijving;
		  uni_link = data.uni_link;
		  fac_naam = data.fac_naam;
		  uni_image = data.uni_image;
		  //console.log(uni_omschrijving);
		  $("#uitgelicht").fadeOut(800);
		  $('#slider').fadeOut(1300, function(){
		  	$("#focus h1").html(uni_naam);
			$("#focus-omschrijving").html(uni_omschrijving);
			$("#focus h2").html(fac_naam);
			$("#uitgelicht-profile").attr("href", uni_link);
			$("#uitgelicht img").attr("src", uni_image);
			$("#uitgelicht").fadeIn(800);
			$('#slider').fadeIn(1300);
		  });
		  
		  //console.log(data);
          
		  setTimeout(function(){
		  	load_uitgelicht();
		  }, uitgelicht_interval);
        });
}

function show_login() {
	$("#login-form").fadeIn('fast');
}

function hide_login() { 
	$("#login-form").fadeOut('slow');
}

//console.log($('div#uitgelicht:not(div.school-detail)').length);

if ($('div#uitgelicht:not(div.school-detail)').length>0){
	setTimeout(function(){
		load_uitgelicht();
	}, uitgelicht_interval);
}
 
$("#login-holder").hoverIntent({
	sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
	interval: 50,   // number = milliseconds for onMouseOver polling interval
	over: show_login,     // function = onMouseOver callback (required)
	timeout: 500,   // number = milliseconds delay before onMouseOut
	out: hide_login       // function = onMouseOut callback (required)
});

	$('#filter-form select option:first-child').css('color', '#cccccc');

	$('.search_result_header').click(function(){
		if ($(this).parent().find('.search_result_items').css('display')=="block"){
			$(this).parent().find('.search_result_items').slideUp();
		}else{
			$(this).parent().find('.search_result_items').slideDown('fast');
		}	
	});
	
	$('#id_region').change(function(){
		if (window.location.href.indexOf('careers') > 0) {
			window.location = '/careers/?region='+$(this).val();
		}else{
			window.location = '/world-list-of-pharmacy-schools/?region='+$(this).val();
		}
	});
	
});
/*
$.fn.hoverClass = function(c) {
    return this.each(function(){
        $(this).hover( 
            function() { $(this).addClass(c);  },
            function() { $(this).removeClass(c); }
        );
    });
}; 


$(document).ready(function(){
    $("#menu li").hover(
        function(){ $("ul", this).fadeIn("slow"); }, 
        function() { } 
    );
    if (document.all) {
        $("#menu li").hoverClass ("sfHover");
    }
});


//end sfjquery
var menu_timeout    = 1000;
var menu_closetimer = 0;
var menu_item = 0;
var menu_parent = 0;

function menu_open(){  
 
    * 
   menu_canceltimer();
   menu_close();
   console.log($(this));
   console.log($(this).parent().attr('id')=="menu");
   console.log($(this).parent().attr('id'));
   menu_parent = $(this);
   
   $(this).find('a').css('color', '#676767');
   if ($(this).find('ul').css('display') != 'block') {
   	menu_item = $(this).find('ul').fadeIn('fast', new function(){
   		console.log('done fade in');
   	});
   }
   
   if ($(this).parent().attr('id') == 'menu') {
   	$(this).addClass('hovering');
   	if ($(this).find('ul').css('display') != 'block') {
   		menu_item = $(this).find('ul');
   		menu_item.fadeIn('fast', new function(){
   			console.log('done fade in');
   		});
   	}
   }
}

function menu_close(){  
	
	if (menu_parent){
		menu_parent.removeClass('hovering');
	}
	if(menu_item){
		menu_item.fadeOut('slow');
		menu_item.parent().removeClass('hovering');
		$('#menu').find('a').css('color', '#ffffff');
		//console.log('hiding');
	} 
	
	if ($(this).hasClass('hovering')){
		console.log($(this));
		$(this).find('ul').fadeOut('slow');
	} 
}

function menu_timer(){  
	menu_closetimer = window.setTimeout(menu_close, menu_timeout);
}

function menu_canceltimer(){  
	if(menu_closetimer){  
		window.clearTimeout(menu_closetimer);
      	menu_closetimer = null;
	}
}
	  
$(document).ready(function() {
	$('#menu li').bind('mouseover', menu_open);
	$('#menu li').bind('mouseout',  menu_timer);
});
 
document.onclick = menu_close;*/
